<?php
namespace app\models;

use yii\db\ActiveRecord;

/**
 * 资讯分类
 *
 * Class ArticleCategory
 * @package app\models
 *
 * @property integer $id
 * @property integer $pid
 * @property string $name
 * @property integer $sort
 *
 * @property array $subModels 关联子分类
 */
class ArticleCategory extends ActiveRecord
{
    /**
     * @inheritDoc
     */
    public function rules()
    {
        return [
            [['pid', 'sort'], 'integer'],
            ['name', 'required'],
            ['name', 'string', 'max'=>256],
        ];
    }

    /**
     * 递归列表用于下拉控件
     * @param integer $pid=null 上级编号
     * @param string $prepend='' 返回名称之前附加的内容（显示上下级效果）
     * @return array($id=>$name)
     */
    public static function list4Options($pid = null, $prepend = '')
    {
        $model_list = ArticleCategory::find()
            ->andWhere(['pid'=>$pid])
            ->orderBy('sort DESC')
            ->all();
        $result = [];
        foreach ($model_list as $model) {
            $result[$model->id] = $prepend . $model->name;
            $sub_model_list = ArticleCategory::list4Options($model->id, $prepend . '　　');
            if (!empty($sub_model_list)) {
                $result = $result + $sub_model_list;
            }
        }
        return $result;
    }

    /**
     * 子分类
     * @return \yii\db\ActiveQuery
     */
    public function getSubModels()
    {
        return $this->hasMany(ArticleCategory::className(), ['pid'=>'id']);
    }

    /**
     * 将涉及到的资讯分类改为上级分类
     * @inheritdoc
     */
    public function afterDelete()
    {
        Article::updateAll(['cid'=>$this->pid], ['cid'=>$this->id]);
        return parent::afterDelete();
    }
}
